package com.bianmaba.batch.example.db.batch;

import com.bianmaba.batch.example.db.bean.Log;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

/**
 * @program: spring-batch-examples
 * @description:
 * @author: Chenjiabin
 * @create: 2019/1/8 11:33
 **/
@Service
public class LogWriter implements ItemWriter<Log> {
    @Autowired
    @Qualifier("dataSource")
    private HikariDataSource dataSource;

    @Override
    public void write(List<? extends Log> list) throws Exception {
        PreparedStatement statement = null;
        Connection connection = null;
        boolean autocommit = false;
        try {
            connection = dataSource.getConnection();
            //记录连接原始提交方式
            autocommit = connection.getAutoCommit();
            connection.setAutoCommit(false);
            statement = connection.prepareStatement("insert into log(id,name,dt,logins) values(?,?,?,?)");
            for (Log log : list) {
                String id = UUID.randomUUID().toString().replaceAll("-", "");
                statement.setString(1, id);
                statement.setString(2, log.getName());
                statement.setString(3, log.getDt());
                statement.setDouble(4, log.getLogins());
                statement.addBatch();
            }
            statement.executeBatch();
            connection.commit();
        } finally {
            statement.clearBatch();
            //还原连接提交方式
            connection.setAutoCommit(autocommit);
            statement.close();
            dataSource.evictConnection(connection);
        }
    }
}
